package chapter08;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class ForkJoinTest {
    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool(1000);
        Integer invoke = forkJoinPool.invoke(new MyTask(5));
        System.out.println(invoke);
    }
}

/**
 * 求 1到n之间的数字和
 */
@Slf4j
class MyTask extends RecursiveTask<Integer> {

    private int n;
    public MyTask(int n){
        this.n=n;
    }

    @Override
    protected Integer compute() {
        if (n<=0) return 0;
        // 拆分业务
        MyTask myTask = new MyTask(n-1);
        myTask.fork();
        Integer nextres = myTask.join();
        // 处理当前业务，耗时2s
        try {
            log.debug("业务{}开始处理",n);
            Thread.sleep(2000);
            log.debug("业务{}处理完毕",n);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.debug("当前业务{}，所分子业务划分结果：{}",n,nextres);
        // 返回当前业务加上下一个业务的和
        return n+nextres;
    }
}
